/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.proc.helper;

import org.ipig.constants.DateTimeCnst;
import org.ipig.constants.SymbolCnst;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * ProcHelper
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: ProcHelper.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
public final class ProcHelper {

    /**
     * 解析时间跨度，将跨度转化为milliseconds
     *
     * @param dur - 如参数为y(年)、M(月)、d(天)、 h(小时)、 m(分钟)、 s(秒)，
     */
    public static Long parseDurPattern(String dur) {
        DateTimeCnst.Pattern pattern = null;
        long milliseconds = 0;
        dur = StringUtils.remove(dur, DateTimeCnst.KEY_TIME_AFTER);
        dur = StringUtils.remove(dur, DateTimeCnst.KEY_TIME_BEFORE);
        dur = StringUtils.remove(dur, DateTimeCnst.KEY_TIME_PATTERN);
        int timeIndex = 0;
        for (int i = 0; i < DateTimeCnst.DATE_KEY_IGNORE_CASE.length; i++) {//不区分大小写
            String timePatternValue = StringUtils.lowerCase(DateTimeCnst.DATE_KEY_IGNORE_CASE[i]);
            timeIndex = StringUtils.indexOfIgnoreCase(dur, timePatternValue);
            if (timeIndex > 0) {
                pattern = DateTimeCnst.Pattern.parse(timePatternValue);
                break;
            }
        }
        if (timeIndex <= 0) {
            for (int i = 0; i < DateTimeCnst.DATE_KEY_CASE_SENSITIVE.length; i++) {//区分大小写
                String timePatternValue = DateTimeCnst.DATE_KEY_CASE_SENSITIVE[i];
                timeIndex = StringUtils.indexOf(dur, timePatternValue);
                if (timeIndex > 0) {
                    pattern = DateTimeCnst.Pattern.parse(timePatternValue);
                    break;
                }
            }
        }
        Long expireNum = 0L;
        if (timeIndex > 0) {
            expireNum = NumberUtils.toLong((new StringBuilder(dur)).deleteCharAt(timeIndex).toString(), 0);
        } else {
            expireNum = NumberUtils.toLong(dur, 0);
        }
        if (pattern == null) {
            pattern = DateTimeCnst.Pattern.DAYS;//默认
        }
        milliseconds = expireNum * pattern.seconds * 1000;
        return milliseconds;
    }

    public static final String getCachedKey(String biz, String dim, String key) {
        StringBuilder sb = new StringBuilder().append(biz).append(SymbolCnst.WELL).append(dim)
                .append(SymbolCnst.WELL).append(key);
        return sb.toString();
    }
}
